<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>Region Switching</title>
</head>

<body>
  <script>
    (function () {
      const DEFAULT_REGION = 'hzh.sealos.run'

      const REGION_MAP = {
        xxx: 'xxx'
      }

      function getUrlParam (name) {
        const url = new URL(window.location.href)
        return url.searchParams.get(name)
      }

      function setLocalStorage (name, value) {
        localStorage.setItem(name, value)
      }

      function getLocalStorage (name) {
        return localStorage.getItem(name)
      }

      function validateRegion (regionId, regionDomain) {
        if (!regionId || !regionDomain) return false
        return REGION_MAP[regionId] === regionDomain
      }

      function buildTargetUrl (targetRegion, pathname, url) {
        let targetUrl = `https://${targetRegion}${pathname}`

        const params = url.search
        if (params) {
          targetUrl += params
        }

        return targetUrl
      }

      function redirect () {
        const url = new URL(window.location.href)
        const regionId = getUrlParam('regionId')
        const regionDomain = getUrlParam('regionDomain')

        const isValid = validateRegion(regionId, regionDomain)

        if (isValid) {
          setLocalStorage('latest_region', regionDomain)
          setLocalStorage('latest_region_id', regionId)

          const targetRegion = regionDomain
          const targetUrl = buildTargetUrl(targetRegion, url.pathname, url)

          window.location.href = targetUrl
        } else {
          const savedRegionId = getLocalStorage('latest_region_id')
          const savedRegion = getLocalStorage('latest_region')

          const isSavedValid = savedRegionId && savedRegion && REGION_MAP[savedRegionId] === savedRegion

          const targetRegion = isSavedValid ? savedRegion : DEFAULT_REGION
          const targetUrl = buildTargetUrl(targetRegion, url.pathname, url)

          window.location.href = targetUrl
        }
      }

      redirect()
    })();
  </script>
</body>

</html>